import React from 'react'
import { inject, observer } from 'mobx-react'
import { DateSwitch, Button, Icon, Select, Tools, Bubble } from 'weaver-mobile'
import { SelectPage } from 'weaver-mobile-page';
import { withRouter } from 'react-router-dom';
import { toJS } from 'mobx';
import WeekDatePicker from '../../util/DatePicker';
import { isIOS, filterBR } from '../../util/util';
import moment from 'moment';
const getLabel = Tools.getLabel;

const store = [
  'oneWeekStore',
  'viewWorkplanStore',
];
@inject(...store)
@withRouter
@observer
export default class OneWeekWorkplan extends React.Component {
  static defaultProps = {
    prefixCls: 'oneweek-workplan'
  }
  constructor() {
    super()
    this.state = {
      value: '0',
    }
  }

  componentDidMount() {
    let pathName = this.props.location.pathname
    if(pathName == "/calendar/myCalendar/report/oneWeekWorkplan"||pathName == "/calendar/allCalendar/report/oneWeekWorkplan"||pathName == "/calendar/myCalendar/report/oneWeekWorkplan/detail"){
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(503461,'一周日程安排') })
    }
    const { getWorkPlanWeekGroupSelect, getWorkPlanWeekData, selectedDate, groupId } = this.props.oneWeekStore;
    getWorkPlanWeekGroupSelect(
      (params) => getWorkPlanWeekData(params)
    );
    if(window.iNoBounce && window.iNoBounce.isEnabled()) {
      isIOS() && window.iNoBounce.disable(); // 解决ios滑动问题
    }
  }

  componentWillUnmount() {
    if(window.iNoBounce && !window.iNoBounce.isEnabled()) {
      isIOS() && window.iNoBounce.enable(); // 组件卸载后，还原解决ios滑动问题时的设置
    }
  }
  componentWillReceiveProps(nextProps){
    let prePathName = this.props.location.pathname
    let curPathName = nextProps.location.pathname
    if(curPathName&&curPathName!==prePathName){
      if(curPathName == "/calendar/myCalendar/report/oneWeekWorkplan"||curPathName == "/calendar/allCalendar/report/oneWeekWorkplan"||curPathName == "/calendar/myCalendar/report/oneWeekWorkplan/detail"){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(503461,'一周日程安排') })
      }
    }
  }
  componentDidUpdate = () => {
    this.getRightHeightToLeft();
  }

  getRightHeightToLeft = () => {
    const {isStyleX} = this.props.oneWeekStore;
    let tableRows = document.getElementsByClassName('table-row');
    let infoHrms = document.getElementsByClassName('info-hrm');
    let left = document.getElementsByClassName('tr-left');
    let right = document.getElementsByClassName('tr-right');
   
    if (infoHrms) { // 超出三行点点  60: 三行的高度
      for (let i = 0; i < infoHrms.length; i++) {
        if (infoHrms[i] && infoHrms[i].clientHeight > 60) {
          let hrminfo = document.getElementsByClassName('info-hrm')[i];
          let height = hrminfo.clientHeight;
          while (height > 60) {
            if (hrminfo.innerText && hrminfo.innerText.length > 100) {
              hrminfo.innerText = hrminfo.innerText.substring(0, 100);
            } else {
              hrminfo.innerText = hrminfo.innerText.substring(0, hrminfo.innerText.length - 5);
            }
            height = document.getElementsByClassName('info-hrm')[i].clientHeight;
          }
          hrminfo.innerText = hrminfo.innerText + '...';
        }
      }
    }
    
    if (isStyleX && left.length > 0 && right.length > 0) { // 左侧高度由右侧内容决定
      for (let j = 0; j < left.length; j++) {
        left[j].style.height = right[j].clientHeight + 'px';
        right[j].style.height = right[j].clientHeight + 'px';
      }
    }
  }

  getWeekContent = (date, groupId) => {
    const { getWorkPlanWeekData } = this.props.oneWeekStore;
    let params = {
      selectDate: date,
      groupId: groupId,
    };
    getWorkPlanWeekData(params);
  }

 getThisWeek = (e) => {
  const { groupId, setState} = this.props.oneWeekStore;
  let date = new Date();
  let dateString =  moment(date).format('YYYY-MM-DD');

  this.getWeekContent(dateString, groupId);
  setState({selectedDate: dateString});
  this.activeStyle(this.refs.weekButton);
 }

changeDate = (params) => {
  if (0 < parseInt(params, 10) && parseInt(params, 10) < 10) {
    return `0${params}`;
  } else {
    return params;
  }
}

 doRefresh = () => {
  const { groupId, selectedDate} = this.props.oneWeekStore;
  this.getWeekContent(selectedDate, groupId);
  this.activeStyle(this.refs.dorefresh);
 }

 changeStyle = () => {
  const { isStyleX, setState } = this.props.oneWeekStore;;
  setState({isStyleX: !isStyleX});
  this.activeStyle(this.refs.displayType);
  Bubble.remind(getLabel('508359','显示样式已切换') ,1);
 }

 activeStyle = (v) => {
  if (v) { // 点击样式
    let beforeActive = v.className;
    v.className = `${v.className} active`;
    setTimeout(()=>{
      v.className = beforeActive;
    }, 100);
  }
 }

  getHeader = () => {
    const { selectedDate, weekStartDate, weekEndDate, isStyleX } = this.props.oneWeekStore;
    const innerWidth = window.innerWidth;
    let marginRight = window.innerWidth > 320 ? '5%' : '';
    let field = [];
    let enStyle = getLabel('15539','本周').indexOf('week') > -1 ? {'font-size':'12px'} : '';
    field.push(
      <div>
        <div className='date-picker' key='date-picker' style={{marginRight: marginRight}}>
          <WeekDatePicker
            visible={false}
            value={selectedDate}
            startDate={weekStartDate}
            endDate={moment(weekEndDate).format("MM-DD")}
            onChange={(v) => this.onPickerChange(v)}
            onOk={(v)=>{ this.datePickerOk(v)}}
          />
        </div>
        <div className='week-button' ref='weekButton'  key='week-button' style={{ ...enStyle }} onClick={(e) => { this.getThisWeek(e) }}><span>{getLabel('15539','本周')}</span></div>
        <div className='do-refresh' ref='dorefresh' key='do-refresh' onClick={() => { this.doRefresh() }}><Icon type='refresh' size='xs'/></div>
        <div className='display-type' ref='displayType' key='display-type' onClick={()=>this.changeStyle()}><Icon type={isStyleX ? 'style-02' : 'style'} size='sm' /></div>

      </div>
    )

    return field;
  }

  toPreviewWorkplan = (workid) => {
    const { location:{ pathname }, viewWorkplanStore, oneWeekStore } = this.props;
    this.props.history.push('detail');
    viewWorkplanStore.changeWorkplanID( workid );
    oneWeekStore.setState({ 
      status: {
        current: 'preview'
      } 
    });
  }

  getWorkplanItem = (arr) => {
    // const {setStatusParams} = this.props.myWorkPlanStore;
    let fields = [];
    arr && arr.map((res, i) => {
      if(res.title) {
        res.title = filterBR(res.title);
      }
      fields.push(
        <div className='info-dispaly' key={i}>
          <div className='info-header'>
            <label>{res.beginTime}</label>
            <span ref='title' className='title' onClick={() => { this.toPreviewWorkplan( res.workid )}}>{res.title}</span>
          </div>
          <div className='info-hrm' id='infoHrmText' >{res.resourceName}</div>
        </div>
      )
    })

    return fields;
  }

  getContentY = () => {
    let field = [];
    let tableTr = [];
    let { oneWeekDatas, showNight, showNoon } = this.props.oneWeekStore;
    oneWeekDatas = toJS(oneWeekDatas);
    if (oneWeekDatas.length > 0) {
      oneWeekDatas instanceof Array && oneWeekDatas.map((res, i) => {
        tableTr.push(
          <tr key={i} className='table-row' ref={`tableRow${i}`}>
            <td className='tr-left'>
              <div>
                <span>{res.date}</span>
                <span className='week'>{res.week}</span>
              </div>
            </td>
            <td className='tr-right' style={{width: window.innerWidth - 94}}>
              <div className='workplan-item'>
                <div className='time-label'><span>{getLabel(512929, '上午')}</span></div>
                <div className='workplan-info'>
                  {this.getWorkplanItem(res.am)}
                </div>
              </div>
              {showNoon && <div className='workplan-item'>
                <div className='time-label'><span>{getLabel('389284','中午') }</span></div>
                <div className='workplan-info'>
                  {this.getWorkplanItem(res.noon)}
                </div>
              </div>}
              <div className='workplan-item'>
                <div className='time-label'><span>{getLabel(512930, '下午')}</span></div>
                <div className='workplan-info'>
                  {this.getWorkplanItem(res.pm)}
                </div>
              </div>
              {showNight && <div className='workplan-item'>
                <div className='time-label'><span>{getLabel(503462, '晚上')}</span></div>
                <div className='workplan-info'>
                  {this.getWorkplanItem(res.night)}
                </div>
              </div>}
            </td>
          </tr>
        )
      })
    }
    field.push(
      this.getScrollHeader('y')
    )
    field.push(
      <div className='scroll-content' key='scroll-content'>
        <table className='table' ref='tableY' cellPadding='0'>
          <tbody>
            {tableTr}
          </tbody>
        </table>
      </div>
    )

    return field;
  }

  getContentX = () => {
    let field = [];
    let tableTr = [];
    let leftContent = [];
    let rightContent = [];
    let { oneWeekDatas, showNight, showNoon } = this.props.oneWeekStore;
    oneWeekDatas = toJS(oneWeekDatas);
    if (oneWeekDatas.length > 0) {
      oneWeekDatas instanceof Array && oneWeekDatas.map((res, i) => {
        leftContent.push(
          <tr className='tr-left' key={i} style={{ height: 'inherit', textAlign: 'center' }}>
            <td>
              <span style={{display: 'inline-block'}}>{res.date}</span>
              <span className='week' style={{display: 'inline-block'}}>{res.week}</span>
            </td>
          </tr>
        )
        rightContent.push(
          <tr className='tr-right' key={i}>
            <td className='workplan-item' style={{height: 'inherit'}}>
              <div className='workplan-info'>
                {this.getWorkplanItem(res.am)}
              </div>
            </td>
            {showNoon && <td className='workplan-item' style={{height: 'inherit'}}>
              <div className='workplan-info'>
                {this.getWorkplanItem(res.noon)}
              </div>
            </td>}
            <td className='workplan-item' style={{height: 'inherit'}}>
              <div className='workplan-info'>
                {this.getWorkplanItem(res.pm)}
              </div>
            </td>
            {showNight && <td className='workplan-item' style={{height: 'inherit'}}>
              <div className='workplan-info'>
                {this.getWorkplanItem(res.night)}
              </div>
            </td>}
          </tr>
        )

      })
    }
    field.push(
      this.getScrollHeader('x')
    )
    field.push(
      <div className='scroll-content' key='scroll-content' ref="tableX">
        <div className='left-scroll' onScroll={this.tableXLeft} ref='tableXLeft'>
          <table cellPadding='0' cellSpacing="0">
            <tbody>
              {leftContent}
            </tbody>
          </table>
        </div>
        <div className='right-scroll' onScroll={this.tableXRight} ref='tableXRight'>
          <table className='scroll-content' cellPadding='0' cellSpacing="0" >
            <tbody >
              {rightContent}
            </tbody>
          </table>
        </div>
      </div>
    )
    
    return field;
  }

  tableXRight = () => {
    if (this.refs.tableXLeft && this.refs.tableXRight && this.refs.headScroll) {
      this.refs.tableXLeft.scrollTop = this.refs.tableXRight.scrollTop;
      this.refs.headScroll.scrollLeft = this.refs.tableXRight.scrollLeft;
    }
  }

  tableXLeft = () => {
    if (this.refs.tableXLeft && this.refs.tableXRight) {
      this.refs.tableXRight.scrollTop = this.refs.tableXLeft.scrollTop;
    }
  }

  headScroll = () => {
    if (this.refs.headScroll && this.refs.tableXRight) {
      this.refs.tableXRight.scrollLeft = this.refs.headScroll.scrollLeft;
    }
  }


  getScrollHeader = (type) => {
    let field = [];
    let { oneWeekDatas, showNight, showNoon } = this.props.oneWeekStore;

    if (type === 'x') {
      field.push(
        <div className='scroll-header' key='scroll-header'>
          <div className='left'></div>
          <div className='right' ref='headScroll' onScroll={this.headScroll} >
            <div className='workplan-item'>
              <div className='time-label'><span>{getLabel(512929, '上午')}</span></div>
            </div>
            {showNoon && <div className='workplan-item'>
              <div className='time-label'><span>{getLabel('389284','中午')}</span></div>
            </div>}
            <div className='workplan-item'>
              <div className='time-label'><span>{getLabel(512930, '下午')}</span></div>
            </div>
            {showNight && <div className='workplan-item'>
              <div className='time-label'><span>{getLabel(503462, '晚上')}</span></div>
            </div>}
          </div>
        </div>
      )
    }
    if (type === 'y') {
      field.push(
        <div className='scroll-header' key='scroll-header'>
          <div className='time-label'>
            {getLabel('19736','时间') }
          </div>
          <div className='content-label'>
            {getLabel('17795','工作内容')}
          </div>
        </div>
      )
    }
    return field;
  }

  getLoadding = () => {
    let field = [];
    field.push(
      <div className='loaidng-icon' key='loading'>
        <Icon type='loading' size='lg' />
      </div>
    );
    return field;
  }

  datePickerOk = (v) => {
    const { groupId } = this.props.oneWeekStore;
    this.getWeekContent(v, groupId);
  }

  onPickerChange = (v) => {
    const { groupId, setState } = this.props.oneWeekStore;
    setState({selectedDate: v});
    this.getWeekContent(v, groupId);
  }

  render() {
    const { prefixCls } = this.props;
    let { selectGroup, selectedType, selectPage, loadding, selectedDate, weekStartDate, weekEndDate, init, isStyleX } = this.props.oneWeekStore;
    let type = isStyleX ? 'x' : 'y';
    selectGroup = toJS(selectGroup);
    selectedType = toJS(selectedType);
    return (
      <div>
        {init && <div className={`${prefixCls}-container`}>
          <div className={`${prefixCls}-container-head`}>
            {this.getHeader()}
          </div>
          <SelectPage
            options={selectGroup}
            store={selectPage}
            valueArray={selectedType}
            label=""
            key='selectpage'
            onChange={(key, showname) => {
              const { setState, selectedDate } = this.props.oneWeekStore;
              let groupId = key[0]&&key[0].key || '-9999';
              this.getWeekContent(selectedDate, groupId);
              setState({ groupId: groupId, selectedType: [groupId] });
            }}
          />
          <div className={`${prefixCls}-container-content-${type}`}>
            {isStyleX ? this.getContentX() : this.getContentY()}
          </div>
        </div>}
        {loadding && this.getLoadding()}
      </div>
    )
  }
}